package org.example;

import org.springframework.core.SpringProperties;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;

/**
 * Hello world!
 *
 */
public class App 
{
    private static final String XML_FILE_EXTENSION = ".xml";
    public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

    private static final boolean shouldIgnoreXml = SpringProperties.getFlag("spring.xml.ignore");
    public static Properties loadProperties(Resource resource) throws IOException {
        Properties props = new Properties();
        fillProperties(props, resource);
        return props;
    }

    /**
     * Fill the given properties from the given resource (in ISO-8859-1 encoding).
     * @param props the Properties instance to fill
     * @param resource the resource to load from
     * @throws IOException if loading failed
     */
    public static void fillProperties(Properties props, Resource resource) throws IOException {
        try (InputStream is = resource.getInputStream()) {
            String filename = resource.getFilename();
            if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {
                if (shouldIgnoreXml) {
                    throw new UnsupportedOperationException("XML support disabled");
                }
                props.loadFromXML(is);
            }
            else {
                props.load(is);
            }
        }
    }
    public static void main( String[] args )
    {
        try {
            //获取配置的核心代码
            Enumeration<URL> urls = App.class.getClassLoader().getResources(FACTORIES_RESOURCE_LOCATION);

            while (urls.hasMoreElements()) {
                System.out.println("========print spring.factories position=======");
                URL url = urls.nextElement();
                System.out.println(url);
                UrlResource resource = new UrlResource(url);
                Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                for (Map.Entry<?, ?> entry : properties.entrySet()) {
                    String factoryTypeName = ((String) entry.getKey()).trim();
                    System.out.println(factoryTypeName);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
